package com.tjf.lib_network.okhttp;

import com.tjf.lib_utils.LogsUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 监听token 过期后进行其他操作
 */
public class TokenInterceptor implements Interceptor {

    TokenCallBack tokenCallBack;

    public TokenInterceptor(TokenCallBack tokenCallBack) {
        this.tokenCallBack = tokenCallBack;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == 200) {
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset UTF8 = Charset.forName("UTF-8");
            String data = buffer.clone().readString(UTF8);//采用复制的方式读取，否则会导致请求异常!
//这判断根据你们后台的具体返回数据进行判断。
// (我们后台会返回token 失效,我以此进行判断，你们也可以让后台返回特定的code进行判断)
            // 签名过期 {"message":"Signature has expired.","error_code":401}
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(data);

                int code = jsonObject.optInt("code");
//                LogsUtils.i("token===", data, code, tokenCallBack != null);
                if (code == 402) {
                    if (tokenCallBack != null) {
                        tokenCallBack.onTokenPastDue();
                    }
                }
            } catch (Exception e) {
//                Log.e("异常=token拦截器=", e.getLocalizedMessage());
            }
        }
        return response;
    }
}